local desc_1v2jbs = [[
  # 私服斗地主模式简介

  ___

  总体规则类似身份局。游戏由三人进行，一人扮演地主（主公），其他两人扮演农民（反贼）。
  开始增加抢地主环节
  地主增加一点体力上限和体力：

  当农民被击杀后，另一名农民可以选择：1.摸两张牌，2.回复一点体力 

  *击杀农民的人没有摸三张牌的奖励。*

  胜利规则与身份局一致。

]]
local Tt= require 'packages/lingling_extra/record/Theorem'

--[[
迷你、game机制分析
loadData 跟普通对话框差不多
通过ClientInstance.notifyServer("PushRequest", "updatemini,select," + root.selected);
这个返回调用minigame的 update_func，弃置data是用逗号隔开的select，等
然后大概是用更新doNotify("UpdateMiniGame", json.encode(data))

--]]

Fk:addMiniGame{
    name = "ling_1v2_selectdizhu",
    qml_path = "packages/lingling_extra/qml/ChooseGeneralFor1v2",
    default_choice = function(player, data)
      return 1
    end,
    update_func = function(player, data)
      local room = player.room
      
      for i, p in ipairs(room.players) do
        p:doNotify("UpdateMiniGame", data)
      end
    end,
}

Fk:addMiniGame{
  name = "ling_1v2_sel",
  qml_path = "packages/lingling_extra/qml/2v2",
  default_choice = function(player, data)
    return table.random(data.me,1)
  end,
  update_func = function(player, data)
    local room = player.room
    local d = player.mini_game_data.data
    if d.friend_id~=0 then
      local friend = room:getPlayerById(d.friend_id)
      friend:doNotify("UpdateMiniGame", data)
    end
  end,
}

-- Because packages are loaded before gamelogic.lua loaded
-- so we can not directly create subclass of gamelogic in the top of lua
local jbs_1v2_getLogic = function()
  local jbs_1v2_logic = GameLogic:subclass("jbs_1v2_logic")

  function jbs_1v2_logic:initialize(room)
    GameLogic.initialize(self, room)
    self.role_table = {nil, nil, {"lord", "rebel", "rebel"}}
  end

  --
  function jbs_1v2_logic:assignRoles()
    local room = self.room
    local n = #room.players
    for i = 1, n do
          local p = room.players[i]
          p.role = "hidden"
          room:setPlayerProperty(p, "role_shown", true)
          room:broadcastProperty(p, "role")
          --获取玩家宝珠
          --local zero=Tt.getplayerhufu(room,p)
          --p.role = p._splayer:getScreenName() --结算显示更好，但身份图标疯狂报错
    end
    --self.start_role = "lord"
    -- for adjustSeats
    room.players[1].role = "lord"

    --算了直接抢吧
    --[[
    local function askfordizhu(room, p,point)
      local choices = {"Cancel"}
      local ch={"jbs1v2_jiaodizhu","jbs1v2_qiangdizhu"}
      table.insert(choices, 1, ch[point])
      local choice = room:askToChoice(p, {
        choices = choices,
        skill_name = "game_rule",
        prompt = "要不要当地主？",
      })
      return choice
    end
    local dizhu_index = 1
    local qiang_index = 1

    -- 叫地主阶段
    for i = 1, n do
        local p = room.players[i]
        local choice = askfordizhu(room, p, 1)
        if choice == "jbs1v2_jiaodizhu" then
            dizhu_index = i--有人叫则结束
            break
        end
    end
    for i = 1, n do
      local p = room.players[i]
      p.role = roles[i]
      if p.role == "lord" then
        room:setPlayerProperty(p, "role_shown", true)
      end
      room:broadcastProperty(p, "role")
    end
    --]]
  end
  
  function jbs_1v2_logic:chooseGenerals()
    local room = self.room ---@type Room
    local generalNum = room:getSettings('generalNum')
    local n = room:getSettings('enableDeputy') and 2 or 1
    local lord = room:getLord()
    room:setCurrent(lord)
    local players = room.players
    table.shuffle(players)
    local generals = room:getNGenerals(#players * generalNum + 2)
    --有ai就，没有叫地主环境了
    local who_lord=players[1]--默认第一个是地主
    local maxpoint=1
    local findai=table.find(players,function(p) return p.id<0 end)
    local req
    if findai then
      room:doBroadcastNotify("ShowToast", Fk:translate("#jbs1v2_mode_findai"))
      goto continue
    end
     req = room:askToMiniGame(players,{
        skill_name = "askforjbs1v2_selectdizhu",
        game_type = "ling_1v2_selectdizhu",
        data_table = {
          [players[1].id] = {
            generals=table.slice(generals, 1, generalNum + 1),
            enable=1,--玩家次序

            index=1,--当前次序
  
         
          },
          [players[2].id] = {
            generals=table.slice(generals, generalNum + 1, generalNum * 2 + 1),
            enable=2,
            index=1,

    
          },
          [players[3].id] = {
            generals=table.slice(generals, generalNum * 2 + 1, generalNum * 3 + 1),
            enable=3,
            index=1,
          },
        }
    })
    --得分最高者为地主,否则一号是地主
    for i,p in ipairs(players) do
      local point= req:getResult(p)
      if point>maxpoint then
        maxpoint=point
        who_lord=p
      end
    end

    for i,p in ipairs(players) do
      if p.id==who_lord.id then
        p.role="lord"
      else
        p.role="rebel"
      end
    end

    --有ai就，没有叫地主环节
  
    ::continue::
    if findai then--有ai就，没有叫地主环境了
      local n = #room.players
      local roles = self.role_table[n]
      for i = 1, n do
        local p = room.players[i]
        p.role = roles[i]
        if p.role == "lord" then
          room:setPlayerProperty(p, "role_shown", true)
        end
        room:broadcastProperty(p, "role")
      end
    end
    for _, p in ipairs(players) do
      room:setPlayerProperty(p, "role_shown", true)
      room:broadcastProperty(p, "role")
    end

    --这时候正式开始选将，农民互通
    local lordlist={}
    local farmerlist={}
    local lord_general={}
    local farmer_general={}
    for i, p in ipairs(players) do
      local arg = table.slice(generals, (i - 1) * generalNum + 1, i * generalNum + 1)
      if p.role == "lord" then
        local count = #generals
        table.insert(arg, generals[count])
        table.insert(arg, generals[count - 1])
        table.insert(lordlist,p)
        table.insert(lord_general,arg)
      else
        table.insert(farmerlist,p)
        table.insert(farmer_general,arg)
      end
      
      
    end
    local req2 = room:askToMiniGame(players, {
      skill_name = "AskForGeneral",
      game_type = "ling_1v2_sel",
      data_table = {
        [lordlist[1].id] = {--地主没有队友
          friend_id = 0,
          me = lord_general[1], friend = {},
          num=n,
        },
        [farmerlist[1].id] = {
          friend_id = farmerlist[2].id,
          me = farmer_general[1], friend = farmer_general[2],
          num=n,
        },
        [farmerlist[2].id] = {
          friend_id = farmerlist[1].id,
          me = farmer_general[2], friend = farmer_general[1],
          num=n,
        },
      }
    })
    for _, p in ipairs(players) do
      local general= req2:getResult(p)

      room:setPlayerGeneral(p, general[1], true, true)
      room:setDeputyGeneral(p, general[2], true, true)
      room:findGeneral(general)
    end
    --[[
    local req = Request:new(players, "AskForGeneral")
    for i, p in ipairs(players) do
      local arg = table.slice(generals, (i - 1) * generalNum + 1, i * generalNum + 1)
      if p.role == "lord" then
        local count = #generals
        table.insert(arg, generals[count])
        table.insert(arg, generals[count - 1])
      end
      
      req:setData(p, { arg, n })
      req:setDefaultReply(p, { arg[1] })
    end
    req:ask()
    for _, p in ipairs(players) do
      local result = req:getResult(p)
      local general, deputy = result[1], result[2]
      room:prepareGeneral(p, general, deputy)
    end
    --]]
    room:askToChooseKingdom(players)
    --农民通牌
    farmerlist[1]:addBuddy(farmerlist[2])
    farmerlist[2]:addBuddy(farmerlist[1])
    for _, p in ipairs(players) do
      room:broadcastProperty(p, "general")
      room:broadcastProperty(p, "deputyGeneral")
    end
    --设置倍率


    room:setBanner("@jbs1v2_mode_POINT",maxpoint)

    --这时候再调一下位置
    local player_circle = {}
    local players =room.players
    local p = 1
  
    for i = 1, #players do
      if players[i].role == "lord" then
        p = i
        break
      end
    end
    for j = p, #players do
      table.insert(player_circle, players[j])
    end
    for j = 1, p - 1 do
      table.insert(player_circle, players[j])
    end
  
    room:arrangeSeats(player_circle)
  end


  function jbs_1v2_logic:attachSkillToPlayers()
    local room = self.room

    local addRoleModSkills = function(player, skillName)
      local skill = Fk.skills[skillName]
      if not skill then
        fk.qCritical("Skill: "..skillName.." doesn't exist!")
        return
      end
      if skill:hasTag(Skill.Lord) then
        return
      end
      if skill:hasTag(Skill.AttachedKingdom) and not table.contains(skill:getSkeleton().attached_kingdom, player.kingdom) then
        return
      end
      room:handleAddLoseSkills(player, skillName, nil, false)
    end
    for _, p in ipairs(room.alive_players) do
      for _, s in ipairs(Fk.generals[p.general]:getSkillNameList(false)) do
        addRoleModSkills(p, s)
      end
      local deputy = Fk.generals[p.deputyGeneral]
      if deputy then
        for _, s in ipairs(deputy:getSkillNameList(false)) do
          addRoleModSkills(p, s)
        end
      end
      if p.role == "lord" then
        room:handleAddLoseSkills(p, "m_feiyang|m_bahu|ling_qiangyi", nil, false)
      end
    end
  end

  return jbs_1v2_logic
end




local jbs_1v2_mode = fk.CreateGameMode{
  name = "ling_1v2_mode",
  minPlayer = 3,
  maxPlayer = 3,
  --rule = "#ling_1v2_mode",
  main_mode = "1v2_mode",

  logic = jbs_1v2_getLogic,
  surrender_func = function(self, playedTime)
    local surrenderJudge = { { text = "time limitation: 2 min", passed = playedTime >= 120 } }
    if Self.role ~= "lord" then
      table.insert(surrenderJudge, { text = "1v2: left you alive", passed = #Fk:currentRoom().alive_players == 2 })
    end

    return surrenderJudge
  end,
  get_adjusted = function (self, player)
    if player.role == "lord" then
      return {hp = player.hp + 1, maxHp = player.maxHp + 1}
    end
    return {}
  end,
  reward_punish = function (self, victim, killer)
    local room = victim.room
    if victim.role == "rebel" then
      for _, p in ipairs(room:getOtherPlayers(victim)) do
        if p.role == "rebel" then
          local choices = {"draw2", "Cancel"}
          if p:isWounded() then
            table.insert(choices, 2, "recover")
          end
          local choice = room:askToChoice(p, {
            choices = choices,
            skill_name = "PickLegacy",
          })
          if choice == "draw2" then
            p:drawCards(2, "game_rule")
          else
            room:recover{
              who = p,
              num = 1,
              recoverBy = p,
              skillName = "game_rule",
            }
          end
        end
      end
    end
  end,
}

Fk:loadTranslationTable{
  ["ling_1v2_mode"] = "伶服斗地主",
  ["#jbs_1v2_rule"] = "挑选遗产",
  ["m_1v2_continue"]="将队友主将作为副将！",
  ["jbs_1v2-intro"]="伶服斗地主",
  [":jbs_1v2-intro"]=[[
  总体规则类似身份局。游戏由三人进行，一人扮演地主（主公），其他两人扮演农民（反贼）。<br>
  <br> 地主增加一点体力上限和体力，且可选双将：
  <br><br>当农民被击杀后，另一名农民可以选择：1.摸两张牌，2.回复一点体力 

  <br><br>*击杀农民的人没有摸三张牌的奖励。*

  <br><br>胜利规则与身份局一致。
  <br><br>启用副将时开启全员双将！]],

    ["jbs1v2_jiaodizhu"]="叫地主(虎符*2)",
    ["jbs1v2_qiangdizhu"]="抢地主(虎符*3)",
    ["jbs1v2_1"]="1分",
    ["jbs1v2_2"]="2分",
    ["jbs1v2_3"]="3分",

    ["askforjbs1v2_selectdizhu"]="选择地主",
  ["@jbs1v2_mode_POINT"]="本局倍率",
  ["#jbs1v2_mode_findai"]="本局有AI，不进行抢地主",
  ["#jbs1v2_mode_islower"]="检测到破产玩家，默认本局倍率1",

  ["@!!pve_baozhu"]="宝珠",
  [":@!!pve_baozhu"]="伶伶服的一种货币，参与活动获取",

  [":jbs_1v2_mode"] = desc_1v2jbs,
}

return jbs_1v2_mode
